using System;
using System.Collections.Generic;
using System.Windows.Forms;
using popLib;

namespace SubtitleHandler
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (args.Length == 3)
            {
                process(args[0], args[1], args[2]);
                return;
            }

            Application.Run(new Form1(args.Length > 0 ? args[0] : ""));
        }

        public static void process(string src, string des, string delayStr)
        {

            string str = FileLib.readFile(src);

            string result = "";
            TimeSpan time1, time2, delay = parseTimeSpan(delayStr);
            string[] lines = StringLib.splitByAny(str, "\r\n".Split(' '));

            foreach (string line in lines)
            {
                if (line.IndexOf("-->") > 0)
                {

                    string[] times = StringLib.splitByAny(line, "-->".Split(' '));
                    time1 = parseTimeSpan(times[0]);
                    time2 = parseTimeSpan(times[1]);

                    result += parseString(time1.Add(delay)) + " --> " + parseString(time2.Add(delay)) + "\r\n";
                }
                else
                {
                    result += line + "\r\n";
                }
            }

            FileLib.writeFile(des, result, false, System.Text.Encoding.Unicode);
        }


        public static TimeSpan parseTimeSpan(string time)
        {
            string[] parts = time.Trim().Split(':');
            int sign = time.StartsWith("-") ? -1 : 1;
            return new TimeSpan(0,
                sign * Math.Abs(NumberLib.getInt(parts[0])),
                sign * Math.Abs(NumberLib.getInt(parts[1])),
                sign * Math.Abs(NumberLib.getInt((parts[2].Split(',')[0]))),
                sign * Math.Abs(NumberLib.getInt((parts[2].Split(',')[1]))));
        }

        public static string parseString(TimeSpan timespan)
        {
            return string.Format("{0}:{1}:{2},{3}", timespan.Hours, timespan.Minutes, timespan.Seconds, timespan.Milliseconds);
        }
    }
}